//
//  DRHomeViewController.m
//  DoctorRen
//
//  Created by Lemon on 2018/11/19.
//

#import "DRHomeViewController.h"
#import "UIButton+DR.h"
#import <MJRefresh/MJRefresh.h>
#import "DRHttpModel.h"
#import "DRHomeDataModel.h"
#import "DRHomeCell.h"
#import "UIViewController+DR.h"
#import <SDWebImage/UIImage+GIF.h>
#import "DHGuidePageHUD.h"

@interface DRHomeViewController ()<UITableViewDelegate , UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *headlineBtn;
@property (weak, nonatomic) IBOutlet UIButton *guideBtn;
@property (weak, nonatomic) IBOutlet UIButton *foodTherapyBtn;
@property (weak, nonatomic) IBOutlet UIButton *dietBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) DRHttpModel *requestModel;
@property (nonatomic, strong) NSMutableArray <DRHomeItem *>*cellDatas;
@property (weak, nonatomic) IBOutlet UILabel *weightLabel;
@property (weak, nonatomic) IBOutlet UILabel *mmHgLabel;
@property (weak, nonatomic) IBOutlet UILabel *bloodsugerLabel;
@property (weak, nonatomic) IBOutlet UIImageView *bgImageView;

@property (nonatomic, strong) DRHomeModel *homeModel;

@end

@implementation DRHomeViewController

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.headlineBtn setHorizontalButton:8];
    [self.guideBtn setHorizontalButton:8];
    [self.foodTherapyBtn setHorizontalButton:8];
    [self.dietBtn setHorizontalButton:8];
    self.tableView.tableFooterView = [UIView new];
//    [SVProgressHUD showWithStatus:@"正在加载";
    NSString *filepath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:@"home_bg.gif" ofType:nil];
    NSData *imagedata = [NSData dataWithContentsOfFile:filepath];
    
    self.bgImageView.image = [UIImage sd_animatedGIFWithData:imagedata];
    [self reloadData:YES];
    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        STRONGSELF
        [strongSelf headerRefresh];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        STRONGSELF
        [strongSelf loadModeData];
    }];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headerRefresh) name:kLoginSuccess object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setKefuButtonHidden:NO];
    if ([self isShowUserGuideLoad]) {
        [self setStaticGuidePage];
        [self presentGuideView];
    }

}

- (BOOL) isShowUserGuideLoad{
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *lastRunVersion = [defaults objectForKey:@"LAST_RUN_VERSION_KEY"];
    if (!lastRunVersion) {
        [defaults setObject:currentVersion forKey:@"LAST_RUN_VERSION_KEY"];
        return YES;
    }else if (![lastRunVersion isEqualToString:currentVersion]) {
        [defaults setObject:currentVersion forKey:@"LAST_RUN_VERSION_KEY"];
        return YES;
    }
    return NO;
    
}

- (void)setStaticGuidePage {
    NSArray *imageNameArray = @[@"插画引导页1",@"插画引导页2",@"插画引导页3"];
    DHGuidePageHUD *guidePage = [[DHGuidePageHUD alloc] dh_initWithFrame:KEY_WINDOW.frame imageNameArray:imageNameArray buttonIsHidden:YES];
    guidePage.slideInto = YES;
    [KEY_WINDOW addSubview:guidePage];
}


-(void) reloadData:(BOOL) isPull{
//    WEAKSELF

    [DRHomeDataModel loadHomeData:self.requestModel andSuccess:^(DRHomeModel * _Nonnull model) {
        NSLog(@"%@", model.consultation);
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        self.weightLabel.text = [NSString stringWithFormat:@"%@KG",model.device.weight];
        self.mmHgLabel.text = [NSString stringWithFormat:@"%@mmHg",model.device.pressure];
        self.bloodsugerLabel.text = [NSString stringWithFormat:@"%@mmol/L",model.device.sugar];
        self.homeModel = model;
        if (isPull) {
            [self.cellDatas removeAllObjects];
        }
        if ( model.consultation.count == 0) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.cellDatas addObjectsFromArray:model.consultation];
            [self.tableView reloadData];
        }
        [SVProgressHUD dismiss];
    } andFail:^(NSError *error) {
        if (error.code == 500) {
            [SVProgressHUD dismiss];
            WEAKSELF
            if (![DRLoginDataModel isLogin]) {
                return ;
            }
            [DRLoginDataModel setIsLogin:NO];
            [self presentAlertViewWithTitle:@"请重新登录" message:@"" confirmTitle:@"确定" handler:^{
                [weakSelf gotoLogin];
            }];
        }else{
            [SVProgressHUD showErrorWithStatus:error.localizedDescription];

        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

-(void) headerRefresh{
    NSLog(@"%d",self.requestModel.isLoading);
    if (self.requestModel.isLoading) {
        return;
    }
    self.requestModel.pageIndex = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self reloadData:YES];
}

-(void) loadModeData{
    if (self.requestModel.isLoading) {
        return;
    }
    self.requestModel.pageIndex += 1;
    [self reloadData:NO];
}
- (IBAction)gotoSearch:(id)sender {
    [self pushWebViewWithUrl:self.homeModel.search];
}
- (IBAction)gotoService:(id)sender {
    [self pushWebViewWithUrl:self.homeModel.kefu];
}
- (IBAction)gotoNews:(id)sender {
//    [self pushWebViewWithUrl:self.homeModel.kefulist];
}
- (IBAction)gotoUserInfo:(id)sender {
    if ([DRLoginDataModel getUserToken].length == 0) {
        [self presentNeedLogin:YES];
        return;
    }
    [self pushDevicesVC];
    [self setKefuButtonHidden:YES];
}


- (IBAction)clickItems:(UIButton *)sender {
    NSString *token = [DRLoginDataModel getUserToken];
    switch (sender.tag) {
        case 0:
            [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/home/consultation?type=1&isBack=1&token=%@",token]];
            break;
        case 1:
            [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/home/consultation?type=2&isBack=1&token=%@",token]];
            break;
        case 2:
            [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/home/consultation?type=3&isBack=1&token=%@",token]];
            break;
        default:
            [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/home/treasure?isBack=1&token=%@", token]];
            break;
    }
    
}

-(DRHttpModel *)requestModel{
    if (!_requestModel) {
        _requestModel = [DRHttpModel new];
        _requestModel.url = DRURL(@"index.php/NewApiIndex/index");
        _requestModel.params = @{@"token" : [DRLoginDataModel getUserToken]};
        _requestModel.type = DRPost;
        _requestModel.pageIndex = 1;
    }
    return _requestModel;
}

-(NSMutableArray<DRHomeItem *> *)cellDatas{
    if (!_cellDatas) {
        _cellDatas = [NSMutableArray new];
    }
    return _cellDatas;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.cellDatas.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DRHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DRHomeCell" forIndexPath:indexPath];
    [cell setItem:self.cellDatas[indexPath.row]];
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //http://rsjkkj.com/dist/#foodDetail?id=36
    NSLog(@"%@",[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/foodDetail?id=%@&token=%@&isBack=1",self.cellDatas[indexPath.row]._id,[DRLoginDataModel getUserToken]]);
    [self pushWebViewWithUrl:[NSString stringWithFormat:@"http://rsjkkj.com/dist/#/foodDetail?id=%@&token=%@&isBack=1",self.cellDatas[indexPath.row]._id,[DRLoginDataModel getUserToken]]];
}

@end
